package com.my.blog.website.controller.admin;

import com.github.pagehelper.PageInfo;
import com.my.blog.website.constant.RedisConst;
import com.my.blog.website.controller.BaseController;
import com.my.blog.website.dto.DingDto;
import com.my.blog.website.dto.Group;
import com.my.blog.website.dto.LogActions;
import com.my.blog.website.exception.TipException;
import com.my.blog.website.modal.Bo.RestResponseBo;
import com.my.blog.website.modal.Vo.*;
import com.my.blog.website.service.IDingSevice;
import com.my.blog.website.service.ILogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * @author geng
 * @title: DingController
 * @projectName my-blog
 * @description: TODO
 * @date 2020/1/10 -- 12:00
 */
@Controller
@RequestMapping("admin/ding")
@Transactional(rollbackFor = TipException.class)
public class DingController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ArticleController.class);
    @Autowired
    private IDingSevice dingSevice;
    @Autowired
    private ILogService logService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 打卡列表
     *
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping(value = "")
    public String index(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "limit", defaultValue = "8") int limit, HttpServletRequest request) {
        UserVo user = this.user(request);
        String orderby = null;
        PageInfo<DingDto> Paginator = null;
        if (user.getGroupName().equals(Group.ADMIN.getType())) {
            LOGGER.info("超级管理员查询打卡列表");
            Paginator = dingSevice.getDingsPage(orderby, page, limit);
        } else {
            LOGGER.info("普通用户查询打卡列表");
            Integer id = user.getUid();
            Paginator = dingSevice.getDingsPageById(id, orderby, page, limit);
        }

        request.setAttribute("dings", Paginator);
        return "admin/ding_list";
    }


    /**
     * 打卡发表
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/publish")
    public String newArticle(HttpServletRequest request) {
        return "admin/ding_edit";
    }

    /**
     * 打卡编辑
     *
     * @param did
     * @param request 编辑时候博客的回显
     * @return
     */
    @GetMapping(value = "/{did}")
    public String editArticle(@PathVariable String did, HttpServletRequest request) {
        DingVo dings = dingSevice.getDings(did);
        if (dings == null) throw new IllegalArgumentException("访问资源不存在");
        request.setAttribute("dings", dings);
        request.setAttribute("active", "ding");
        return "admin/ding_edit";
    }

    /**
     * 打卡发表
     *
     * @param dingVo
     * @param request
     * @return
     */
    @PostMapping(value = "/publish")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public RestResponseBo publishArticle(DingVo dingVo, HttpServletRequest request) {
        UserVo users = this.user(request);
        dingVo.setAuthorId(users.getUid());
        try {
            dingSevice.publish(dingVo);
        } catch (Exception e) {
            String msg = "打卡发布失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponseBo.fail(msg);
        }
        if (stringRedisTemplate.hasKey(RedisConst.REDIS_DING)) {
            LOGGER.info("delete redis UserList");
            stringRedisTemplate.delete(RedisConst.REDIS_DING);
        }
        return RestResponseBo.ok();
    }

    /**
     * 打卡更新
     *
     * @param dingVo
     * @param request
     * @return
     */
    @PostMapping(value = "/modify")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public RestResponseBo modifyArticle(DingVo dingVo, HttpServletRequest request) {
        UserVo users = this.user(request);
        dingVo.setAuthorId(users.getUid());
        try {
            dingSevice.updateDing(dingVo);
        } catch (Exception e) {
            String msg = "打卡编辑失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponseBo.fail(msg);
        }
        return RestResponseBo.ok();
    }

    /**
     * 删除打卡
     *
     * @param did
     * @param request
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public RestResponseBo delete(@RequestParam int did, HttpServletRequest request) {
        try {
            dingSevice.deleteByCid(did);
            logService.insertLog(LogActions.DEL_DING.getAction(), did + "", request.getRemoteAddr(), this.getUid(request));
        } catch (Exception e) {
            String msg = "打卡删除失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponseBo.fail(msg);
        }
        if (stringRedisTemplate.hasKey(RedisConst.REDIS_DING)) {
            LOGGER.info("delete redis UserList");
            stringRedisTemplate.delete(RedisConst.REDIS_DING);
        }
        return RestResponseBo.ok();
    }
}
